package net.narusas.aceauction.push;

import java.util.Date;
import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Session;

import net.narusas.aceauction.push.db.DeviceDAO;
import net.narusas.aceauction.push.db.HibernateUtil;
import net.narusas.aceauction.push.db.MessageDAO;
import net.narusas.aceauction.push.model.Device;
import net.narusas.aceauction.push.model.Message;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
public class AuctionPushService {
	MessageDAO messageDAO;
	DeviceDAO deviceDAO;
	PushServiceGateway pushServiceGateway;
	
	public void pushText(String message){
		List<Device> all = deviceDAO.getAll();
		pushServiceGateway.pushText(all, message);
	}
	
	public void pushMessage() {
		Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
//		Session session = HibernateUtil.getInstance().openSession();
		
		session.setFlushMode(FlushMode.MANUAL);
		session.beginTransaction();
		List<Message> messages = messageDAO.findByOvertimed(new Date());
		
		for (Message message : messages) {
			log.info("전송할 메시지: {}", message);
			pushServiceGateway.pushText(message.getDevice(), message.getText());
			message.setDone(true);
			messageDAO.update(message);
		}
		
		session.flush();
		session.close();
	}
	
}
